package com.dure.hotmemory.scenes;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.dure.commonlib.util.FileUtils;
import com.dure.commonlib.util.ImageUtil;
import com.dure.commonlib.util.PreferencesUtils;
import com.dure.commonlib.util.ToastUtils;
import com.dure.commonlib.widgets.CircleImageView;
import com.dure.hotmemory.R;
import com.dure.hotmemory.bean.Bean;
import com.dure.hotmemory.bean.User;
import com.dure.hotmemory.controllers.UserInfoController;
import com.dure.hotmemory.drawview.BaseSurfaceView;
import com.dure.hotmemory.listeners.ConfirmListener;
import com.dure.hotmemory.utils.DialogUtil;
import com.dure.hotmemory.utils.ShowSelectPictureDialogUtil;

import java.io.File;

/**
 * Created by leix on 12/12/2016.
 */

public class UserInfoScene extends BaseScene {
    FrameLayout backFL;

    TextView phoneET;
    EditText nameET;
    EditText ageET;
    EditText careerET;
    EditText emailET;
    TextView manTV;
    TextView womanTV;
    TextView pwdChangeTV;
    CircleImageView headIV;

    Button confirmBtn;
    private LinearLayout phoneLL;

    private int selectedSex = -1;
    private int userSex = -1;// 如果不为-1说明用户已选择过了性别， 就不能再选择了
    private String phone;

    private ShowSelectPictureDialogUtil showSelectPictureDialog;

    private String fileRootDir;
    private String savaFilePath;

    private static final int PHOTO_GRAPH = 1;// 拍照
    private static final int PHOTO_ZOOM = 2; // 缩放
    private static final int PHOTO_RESOULT = 3;// 结果
    private static final String IMAGE_UNSPECIFIED = "image/*";
    UserInfoController controller;
    boolean infoChanged;
    private User user;

    public UserInfoScene(BaseSurfaceView baseSurfaceView) {
        super(baseSurfaceView);
        controller = new UserInfoController(this);
        initData();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            backFL.setBackgroundResource(R.drawable.white_planet_drawable);
        }else{
            backFL.setBackgroundResource(R.drawable.white_circle_drawable);
        }
    }

    @Override
    public void initData() {
        sceneView = LayoutInflater.from(activity).inflate(R.layout.user_info_layout, null);
        findViews();
        addListener();
        initView();
        controller.getUserInfo();
        activity.hideAd();
    }

    private void findViews() {
        backFL = (FrameLayout) sceneView.findViewById(R.id.back_fl);
        headIV = (CircleImageView) sceneView.findViewById(R.id.head_iv);
        womanTV = (TextView) sceneView.findViewById(R.id.woman_tv);
        manTV = (TextView) sceneView.findViewById(R.id.man_tv);
        emailET = (EditText) sceneView.findViewById(R.id.email_et);
        careerET = (EditText) sceneView.findViewById(R.id.career_et);
        ageET = (EditText) sceneView.findViewById(R.id.age_et);
        nameET = (EditText) sceneView.findViewById(R.id.name_et);
        phoneET = (TextView) sceneView.findViewById(R.id.phone_et);
        confirmBtn = (Button) sceneView.findViewById(R.id.confirm_btn);
        pwdChangeTV = (TextView) sceneView.findViewById(R.id.pwd_change_tv);
        phoneLL = (LinearLayout) sceneView.findViewById(R.id.phone_ll);


    }

    private void addListener() {
        backFL.setOnClickListener(activity);
        headIV.setOnClickListener(activity);
        womanTV.setOnClickListener(activity);
        manTV.setOnClickListener(activity);
        confirmBtn.setOnClickListener(activity);
        pwdChangeTV.setOnClickListener(activity);
    }

    private void initView() {


        fileRootDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        savaFilePath = fileRootDir + "/temp.jpg";
        // 初始化头像修改选择项
        showSelectPictureDialog = new ShowSelectPictureDialogUtil(activity,
                new ImpSelectPicture());


    }

    private void setData() {

        phone = PreferencesUtils.getString(context, "phone");

        if (!TextUtils.isEmpty(phone)) {
            phoneET.setText(phone);
        } else {
            phoneLL.setVisibility(View.GONE);
            pwdChangeTV.setText("绑定手机");
        }

        if (!TextUtils.isEmpty(user.name)) {
            nameET.setText(user.name);
//            nameET.setBackgroundResource(R.color.transparent);
        } else {
            user.name = "";
        }
        if (!TextUtils.isEmpty(user.image)) {
            setHeadImg(user.image);
            PreferencesUtils.putString(context, "head_img", user.image);
            PreferencesUtils.putString(context, "name", user.name);
        } else {
            user.image = "";
        }

        if (!TextUtils.isEmpty(user.age)) {
            ageET.setText(user.age);
        } else {
            user.age = "";
        }

        if (!TextUtils.isEmpty(user.player)) {
            careerET.setText(user.player);
        } else {
            user.player = "";
        }

        if (!TextUtils.isEmpty(user.email)) {
            emailET.setText(user.email);
        } else {
            user.email = "";
        }

        if (!TextUtils.isEmpty(user.sex)) {
            setSex(user.sex);
            selectedSex = userSex;
        } else {
            user.sex = "";
            womanTV.setTextColor(context.getResources().getColor(R.color.gray));
            manTV.setTextColor(context.getResources().getColor(R.color.gray));
        }

        String url = PreferencesUtils.getString(context, "head_img");

        if (!TextUtils.isEmpty(url))
            setHeadImg(url);
    }


    @Override
    public void handleRequestSuccess(Bean bean) {
        controller.handleRequestSuccess(bean);
    }

    @Override
    public void handleBack() {
//        activity.showAd();
    }

    public void handleBindSuccessBack(){
        user.phone = PreferencesUtils.getString(activity, "phone");
        pwdChangeTV.setText("修改密码");
    }

    @Override
    public void viewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_fl:
                activity.onBackPressed();
                break;
            case R.id.man_tv:
                if (userSex == -1) {
                    selectedSex = 1;
                    setSex("1");
                }
                break;
            case R.id.woman_tv:
                if (userSex == -1) {
                    selectedSex = 0;
                    setSex("0");
                }
                break;
            case R.id.pwd_change_tv:
                if (!TextUtils.isEmpty(user.phone)) {//修改密码
                    DialogUtil.showModifyPwdDialog(activity, new ConfirmListener() {
                        @Override
                        public void confirmed(Bundle bundle) {
                            String pwd = bundle.getString("password");
                            String newPwd = bundle.getString("new_password");

                            controller.modifyPwd(pwd, newPwd);

                        }
                    });
                }else{// 绑定手机
                    DialogUtil.showBindPhoneDialog(activity, new ConfirmListener() {
                        @Override
                        public void confirmed(Bundle bundle) {
                            String type = bundle.getString("type");
                            String phone = bundle.getString("phone");
                            String pwd = bundle.getString("password");
                            String code = bundle.getString("code");

                            if (TextUtils.equals(type, "bind")) {// 绑定手机
                                controller.bindPhone(phone, pwd, code);
                            }
                            else if (TextUtils.equals(type, "code")) {// 验证码
                                controller.getPhoneCode(phone);
                            }

                        }
                    });
                }
                break;
            case R.id.head_iv:
                showSelectPictureDialog.show();
                break;
            case R.id.confirm_btn:

                String nameStr = nameET.getText().toString().trim();

                if (TextUtils.isEmpty(nameStr)) {
                    ToastUtils.show(context, "昵称不能为空");
                    return;
                }

                if (selectedSex == -1) {
                    ToastUtils.show(context, "请选择您的性别");
                    return;
                }

                String ageStr = ageET.getText().toString();
                String playerStr = careerET.getText().toString();
                String emailStr = emailET.getText().toString();

                if (TextUtils.equals(nameStr, user.name)
                        && TextUtils.equals(ageStr, user.age)
                        && TextUtils.equals(playerStr, user.player)
                        && TextUtils.equals(emailStr, user.email)
                        && Integer.valueOf(user.sex) == selectedSex) {
                    infoChanged = false;
                } else {
                    infoChanged = true;
                }
                if (!infoChanged) {
                    ToastUtils.show(activity, "信息没有改动， 无需提交");
                    return;
                }

                doConfirm();
                break;
        }
    }

    private void setSex(String sex) {
        if (TextUtils.equals(sex, "0")) {
            userSex = 0;
            womanTV.setTextColor(context.getResources().getColor(R.color.light_blue));
            manTV.setTextColor(context.getResources().getColor(R.color.gray));
        } else {
            userSex = 1;
            manTV.setTextColor(context.getResources().getColor(R.color.light_blue));
            womanTV.setTextColor(context.getResources().getColor(R.color.gray));
        }
    }


    private void doConfirm() {

        String nameStr = nameET.getText().toString();
        String ageStr = ageET.getText().toString();
        String playerStr = careerET.getText().toString();
        String emailStr = emailET.getText().toString();

        controller.updateUserInfo(nameStr, String.valueOf(selectedSex), ageStr, playerStr, emailStr);

    }

    private void setHeadImg(final String url) {

        activity.executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    final Bitmap bitmap = ImageUtil.getBitmapFromUrl(url);

                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            headIV.setBitmap(bitmap);
                        }
                    }, 1000);

                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        });
    }

    public void updateInfoBackHandle() {
        userSex = selectedSex;
        PreferencesUtils.putString(context, "name", nameET.getText().toString());

//                baseSurfaceView.destroyScene(Scene.User_Info);
//                context.removeScene();
        activity.onBackPressed();
    }

    public void handleUploadBack(String image) {
        PreferencesUtils.putString(activity, "head_img", image);

        setHeadImg(image);
        File file = new File(savaFilePath);
        if (file.exists()) {
            file.delete();
        }
    }

    public void setUser(User user) {
        this.user = user;
        setData();
    }


//    @Override
//    public void permissionGranted() {
//        getImgFromCamera();
//    }


    public class ImpSelectPicture implements ShowSelectPictureDialogUtil.SelectPictureInterface {

        @Override
        public void takePhoto() {// 拍照取图
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {// 6.0版本以后的要进行动态授权
                if (context.checkSelfPermission(Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    activity.requestPermissions(new String[]{Manifest.permission.CAMERA},
                            1);
                } else {
                    getImgFromCamera();
                }
            } else {
                getImgFromCamera();
            }


        }

        @Override
        public void takePhotoAlbum() {// 图库取图
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    IMAGE_UNSPECIFIED);
            activity.startActivityForResult(intent, PHOTO_ZOOM);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 拍照
        if (requestCode == PHOTO_GRAPH) {
            startPhotoZoom(Uri.fromFile(new File(fileRootDir, "temp.jpg")));
        }
        if (data == null)
            return;
        // 图库
        if (requestCode == PHOTO_ZOOM) {
            startPhotoZoom(data.getData());

        }
        // 处理裁剪的图片
        if (requestCode == PHOTO_RESOULT) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                Bitmap photo = extras.getParcelable("data");
                headIV.setBitmap(photo);
                // 将裁剪之后的图片保存到缓存文件中
                FileUtils.bitmapWriteToCacheDir(photo, savaFilePath);

                File file = new File(savaFilePath);

               controller.uploadImg(file);

            }
        }

    }

    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");// 调用Android系统自带的一个图片剪裁页面,
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");// 进行修剪
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        activity.startActivityForResult(intent, PHOTO_RESOULT);

    }

    public void getImgFromCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (FileUtils.createFile(savaFilePath)) {// 文件创建成功
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(fileRootDir, "temp.jpg")));
            activity.startActivityForResult(intent, PHOTO_GRAPH);
        }
    }

}
